package com.sunlands.zlcx.usercenter.common.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunlands.zlcx.usercenter.vo.response.BusinessResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.sunlands.zlcx.usercenter.vo.CommonResultMessage.NO_AUTH;

/**
 * auth filter中的权限拦截异常处理
 * @author anjl
 * @date 11:24 AM 2019/6/6
 * description:
 */
public class AccessDeniedExceptionHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=UTF-8");
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        BusinessResult<String> result = BusinessResult.createInstance(NO_AUTH.code.longValue(), "权限不足  ", request.getServletPath() + "  " + accessDeniedException.getMessage());
        response.getWriter().write(mapper.writeValueAsString(result));
    }
}
